package com.example.demo.wasu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.test001.HttpUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ShanDongReadLogSend2 {

    private static String urlIp = "http://124.132.254.4:8080";
    public static void scanLogSendUrl() throws IOException {
        File file = new File("/data/logs/galaxy-api-server/");
        File []  files = file.listFiles();
        for (File f :
                files) {
            if(f.getName().matches("galaxy-api.log.2020-02-2[1-3]\\.log")){
                System.out.println("~~~~~~~~~~~"+f.getName());
                List<String> lineList = FileUtils.readLines(f);
                List list = new ArrayList();
                for (String line :
                        lineList) {
                    if(line.contains(",param[")){
                        String urlPrefix = getUrlPrefix(line);
                        String urlSuffix = getUrlSuffix(line);
                        String url = urlPrefix+"?"+urlSuffix;
                        boolean b = sendUrl(url);
                        if(!b){
                            // 失败的话则
                            System.out.println("失败");
                            list.add(url);
                            FileUtils.writeLines(new File("/data/wasu/fail.log"),"utf-8",list,true);
                            list.clear();
                        }else{
                            System.out.println("成功");
                        }
                    }
                }
            }
        }

    }

    private static String getUrlPrefix(String line) {
        String url = null;
        if(line.contains("t_broadcast_control_records")){
            url = urlIp+"/api/broadcast_records";
        } else if(line.contains("t_user_access_records")){
            url = urlIp+"/api/user_acess_records";
        }else if(line.contains("t_pay_situation_records")){
            url = urlIp+"/api/pay_situation_records";
        }
        return url;
    }
    private static String getUrlSuffix(String str) {
        str = str.substring(str.indexOf(",param[")+",param[".length());
        if(str.contains("]")){
            str = str.substring(0,str.indexOf("]"));
        }
        str = str.replace(":","=").replace(",","&");
        return  str;
    }

    private static boolean sendUrl(String url){
        String result = HttpUtils.sendGet(url);
        boolean b = false;
        if(StringUtils.isEmpty(result)){
            return b;
        }
        JSONObject jsonObject = JSON.parseObject(result);
        if(jsonObject == null){
            return b;
        }
        if(String.valueOf(0).equals(jsonObject.get("code").toString())){
            return true;
        }
        return false;
    }
}
